package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.index.qual.SameLen;
import org.example.common.R;
import org.example.pojo.entity.ApComment;
import org.example.pojo.entity.WmNews;
import org.example.pojo.vo.WmNewsVoPage;
import org.example.service.ApCommentService;
import org.example.service.WmNewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "后台文章接口")
@RestController
@RequestMapping("api/article")
@Slf4j
public class SysArticleController {


    @Autowired
    private WmNewsService wmNewsService;

    @Autowired
    private ApCommentService commentService;


    /**
     * 获取文章列表数据
     *
     * @param page
     * @param size
     * @param title
     * @param name
     * @param startTime
     * @param endTime
     * @return
     */
    @GetMapping("/list")
    public R getArticleList(@RequestParam(required = false) Integer page, @RequestParam(required = false) Integer size,
                            @RequestParam(required = false) String title, @RequestParam(required = false) String name,
                            @RequestParam(required = false) String startTime,
                            @RequestParam(required = false) String endTime) {
        log.info("page:{},size:{},title:{},name:{},startTime:{},endTime:{}", page, size, title, name, startTime, endTime);
        Page<WmNewsVoPage> articleList = wmNewsService.getArticleList(page, size, title, name, startTime, endTime);
        return R.ok(articleList);
    }


    /**
     * 删除成功
     *
     * @param id
     * @return
     */
    @DeleteMapping("/remove/{id}")
    public R remove(@PathVariable String id) {
        wmNewsService.removeById(id);
        LambdaQueryWrapper<ApComment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApComment::getNewsId, id);
        List<ApComment> list = commentService.list(wrapper);
        List<Integer> listIds = list.stream().map(ApComment::getId).collect(Collectors.toList());
        commentService.removeBatchByIds(listIds);
        return R.ok("删除成功");
    }

    /**
     * 查询文章详情
     *
     * @param id
     * @return
     */
    @GetMapping("/detail/{id}")
    public R detail(@PathVariable String id) {
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNews::getId, id);
        WmNews news = wmNewsService.getById(id);
        return R.ok(news);
    }
}
